/**
 * 订单控制器
 */

// 引入错误类
const { NotFoundError, ForbiddenError, UnauthorizedError, BadRequestError } = require('../../utils/api-error');

// 引入数据库模型
const { Order, OrderItem, Product, User, sequelize } = require('../../models');
const Address = require('../../models/address');
const Cart = require('../../models/cart');

// 引入共享常量
const { ORDER } = require('../../shared/constants');

// 订单状态枚举 - 使用常量中定义的整数值
const ORDER_STATUS = ORDER.STATUS;

// 引入xml2js和wxpay模块
const xml2js = require('xml2js');
const wxpay = require('../../utils/wxpay');

/**
 * 获取最近订单列表
 */
exports.getRecentOrders = async (req, res, next) => {
  try {
    // 检查用户是否已登录
    if (!req.user) {
      throw new UnauthorizedError('请先登录后查看订单');
    }

    const userId = req.user.id;
    
    // 获取用户的最近订单(限制3条)
    const orders = await Order.findAll({
      where: { user_id: userId },
      limit: 3,
      order: [['create_time', 'DESC']],
      include: [{
        model: OrderItem,
        as: 'items',
        include: [{
          model: Product,
          attributes: ['id', 'name', 'cover', 'price']
        }]
      }]
    });

    // 格式化订单数据
    const formattedOrders = orders.map(order => ({
      id: order.id,
      orderNo: order.order_no,
      total: order.total_amount,
      status: order.status,
      statusText: getStatusText(order.status),
      createdAt: order.create_time,
      items: order.items.map(item => ({
        id: item.id,
        productId: item.product_id,
        quantity: item.quantity,
        price: item.price,
        product: item.Product ? {
          id: item.Product.id,
          name: item.Product.name,
          image: item.Product.cover,
          price: item.Product.price
        } : null
      }))
    }));

    // 返回订单列表
    return res.json({
      code: 0,
      message: '获取订单成功',
      data: formattedOrders
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取订单列表
 */
exports.getOrders = async (req, res, next) => {
  try {
    // 检查用户是否已登录
    if (!req.user) {
      throw new UnauthorizedError('请先登录后查看订单');
    }

    const userId = req.user.id;
    const { page = 1, size = 10, status } = req.query;
    
    // 查询条件
    const where = { user_id: userId };
    if (status) {
      where.status = status;
    }
    
    // 分页选项
    const offset = (page - 1) * size;
    const limit = parseInt(size);
    
    // 获取订单列表
    const { count, rows: orders } = await Order.findAndCountAll({
      where,
      offset,
      limit,
      order: [['create_time', 'DESC']],
      include: [{
        model: OrderItem,
        as: 'items',
        include: [{
          model: Product,
          attributes: ['id', 'name', 'cover', 'price']
        }]
      }]
    });
    
    // 格式化订单数据
    const formattedOrders = orders.map(order => ({
      id: order.id,
      orderNo: order.order_no,
      totalAmount: order.total_amount,
      status: order.status,
      statusText: getStatusText(order.status),
      createdAt: order.create_time,
      items: order.items.map(item => ({
        id: item.id,
        productId: item.product_id,
        quantity: item.quantity,
        price: item.price,
        product: item.Product ? {
          id: item.Product.id,
          name: item.Product.name,
          image: item.Product.cover,
          price: item.Product.price
        } : null
      }))
    }));
    
    // 返回订单列表和分页信息
    return res.json({
      code: 0,
      message: '获取订单成功',
      data: {
        total: count,
        currentPage: parseInt(page),
        pageSize: limit,
        list: formattedOrders
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取订单详情
 */
exports.getOrderById = async (req, res, next) => {
  try {
    // 检查用户是否已登录
    if (!req.user) {
      throw new UnauthorizedError('请先登录后查看订单');
    }

    const userId = req.user.id;
    const orderId = req.params.id;
    
    console.log(`[订单控制器] 查询订单详情: ${orderId}, 用户ID: ${userId}`);
    
    // 从数据库查询订单
    const order = await Order.findOne({
      where: { id: orderId },
      include: [{
        model: OrderItem,
        as: 'items',
        include: [{
          model: Product,
          attributes: ['id', 'name', 'cover', 'price']
        }]
      }]
    });
    
    // 如果订单不存在，抛出404错误
    if (!order) {
      console.log(`[订单控制器] 未找到订单: ${orderId}`);
      throw new NotFoundError(`订单#${orderId}不存在`, 'ORDER_NOT_FOUND');
    }
    
    // 检查是否是用户自己的订单
    if (order.user_id !== userId && order.user_id !== userId.toString()) {
      console.log(`[订单控制器] 用户无权访问订单: 订单用户ID=${order.user_id}, 当前用户ID=${userId}`);
      throw new ForbiddenError('您无权查看此订单', 'ORDER_ACCESS_DENIED');
    }
    
    // 格式化订单数据
    const formattedOrder = {
      id: order.id,
      orderNo: order.order_no,
      totalAmount: order.total_amount,
      status: order.status,
      statusText: getStatusText(order.status),
      address: order.address_snapshot, // 使用地址快照
      createdAt: order.create_time,
      payTime: order.pay_time,
      deliveryTime: order.delivery_time,
      receiveTime: order.receive_time,
      items: order.items.map(item => ({
        id: item.id,
        productId: item.product_id,
        quantity: item.quantity,
        price: item.price,
        product: item.Product ? {
          id: item.Product.id,
          name: item.Product.name,
          image: item.Product.cover,
          price: item.Product.price
        } : item.product_snapshot // 如果没有关联产品，使用快照
      }))
    };
    
    // 返回订单详情
    return res.json({
      code: 0,
      message: '获取订单成功',
      data: formattedOrder
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 取消订单
 */
exports.cancelOrder = async (req, res, next) => {
  try {
    // 检查用户是否已登录
    if (!req.user) {
      throw new UnauthorizedError('请先登录后操作');
    }

    const userId = req.user.id;
    const orderId = req.params.id;
    
    // 查询订单
    const order = await Order.findByPk(orderId);
    
    // 如果订单不存在，抛出404错误
    if (!order) {
      throw new NotFoundError(`订单#${orderId}不存在`, 'ORDER_NOT_FOUND');
    }
    
    // 检查是否是用户自己的订单
    if (order.user_id.toString() !== userId.toString()) {
      throw new ForbiddenError('您无权操作此订单', 'ORDER_ACCESS_DENIED');
    }
    
    // 检查订单状态是否可取消（只有待付款状态可以取消）
    if (order.status !== ORDER_STATUS.PENDING_PAYMENT) {
      throw new BadRequestError('只有待付款的订单可以取消', 'ORDER_STATUS_ERROR');
    }
    
    // 更新订单状态为已取消
    await order.update({
      status: ORDER_STATUS.CANCELLED
    });
    
    // 返回成功结果
    return res.json({
      code: 0,
      message: '订单取消成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 根据状态获取状态文本
 * @param {String} status - 订单状态
 * @returns {String} 状态文本
 */
function getStatusText(status) {
  switch (status) {
    case ORDER_STATUS.PENDING_PAYMENT:
      return '待付款';
    case ORDER_STATUS.PENDING_DELIVERY:
      return '待发货';
    case ORDER_STATUS.PENDING_RECEIPT:
      return '待收货';
    case ORDER_STATUS.COMPLETED:
      return '已完成';
    case ORDER_STATUS.CANCELLED:
      return '已取消';
    default:
      return '未知状态';
  }
}

/**
 * 创建订单
 * 接收购物车商品ID列表，地址ID和备注信息，创建新订单
 */
exports.createOrder = async (req, res, next) => {
  // 使用事务确保数据一致性
  const transaction = await sequelize.transaction();
  
  try {
    // 检查用户是否已登录
    if (!req.user) {
      throw new UnauthorizedError('请先登录后操作');
    }

    const userId = req.user.id;
    const { cartIds, addressId, remark = '' } = req.body;
    
    // 验证必要参数
    if (!cartIds || !Array.isArray(cartIds) || cartIds.length === 0) {
      throw new BadRequestError('请选择要结算的商品');
    }
    
    if (!addressId) {
      throw new BadRequestError('请选择收货地址');
    }
    
    console.log(`[订单控制器] 创建订单请求: 用户=${userId}, 购物车项=${cartIds.join(',')}, 地址ID=${addressId}`);
    
    // 1. 查询购物车中选中的商品信息
    const cartItems = await Cart.findAll({
      where: {
        id: cartIds,
        user_id: userId
      },
      include: [{
        model: Product,
        attributes: ['id', 'name', 'cover', 'price', 'stock']
      }],
      transaction
    });
    
    if (cartItems.length === 0) {
      throw new BadRequestError('所选商品不存在或已被删除');
    }
    
    // 2. 验证商品库存是否充足
    for (const item of cartItems) {
      if (!item.Product) {
        throw new BadRequestError(`商品#${item.product_id}不存在或已下架`);
      }
      
      if (item.Product.stock < item.quantity) {
        throw new BadRequestError(`商品"${item.Product.name}"库存不足`);
      }
    }
    
    // 3. 查询地址信息
    const address = await Address.findOne({
      where: {
        id: addressId,
        user_id: userId
      },
      transaction
    });
    
    if (!address) {
      throw new BadRequestError('收货地址不存在');
    }
    
    // 4. 计算订单总金额
    let totalAmount = 0;
    for (const item of cartItems) {
      totalAmount += item.Product.price * item.quantity;
    }
    
    // 5. 生成订单号 - 格式：年月日+6位随机数
    const date = new Date();
    const dateStr = date.getFullYear() +
                   String(date.getMonth() + 1).padStart(2, '0') +
                   String(date.getDate()).padStart(2, '0');
    const randomStr = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
    const orderNo = dateStr + randomStr;
    
    // 6. 创建收货地址快照
    const addressSnapshot = {
      id: address.id,
      receiver: address.receiver,
      phone: address.phone,
      province: address.province,
      city: address.city,
      district: address.district,
      detail: address.detail,
      isDefault: address.is_default
    };
    
    // 7. 创建订单记录
    const order = await Order.create({
      order_no: orderNo,
      user_id: userId,
      total_amount: totalAmount,
      pay_amount: totalAmount, // 暂不考虑优惠
      freight_amount: 0, // 暂不考虑运费
      address_snapshot: addressSnapshot,
      status: ORDER_STATUS.PENDING_PAYMENT,
      remark: remark
    }, { transaction });
    
    // 8. 创建订单商品记录
    const orderItems = [];
    for (const item of cartItems) {
      // 创建商品快照
      const productSnapshot = {
        id: item.Product.id,
        name: item.Product.name,
        image: item.Product.cover,
        price: item.Product.price
      };
      
      // 创建订单商品
      const orderItem = await OrderItem.create({
        order_id: order.id,
        product_id: item.product_id,
        product_snapshot: productSnapshot,
        quantity: item.quantity,
        price: item.Product.price,
        total_amount: item.Product.price * item.quantity
      }, { transaction });
      
      orderItems.push(orderItem);
      
      // 减少商品库存（如果需要的话）
      // await item.Product.decrement('stock', { by: item.quantity, transaction });
    }
    
    // 9. 从购物车中移除已结算的商品
    await Cart.destroy({
      where: {
        id: cartIds,
        user_id: userId
      },
      transaction
    });
    
    // 提交事务
    await transaction.commit();
    
    console.log(`[订单控制器] 订单创建成功，ID: ${order.id}, 订单号: ${order.order_no}`);
    
    // 返回创建的订单数据
    return res.status(201).json({
      code: 0,
      message: '订单创建成功',
      data: {
        orderId: order.id,
        orderNo: order.order_no
      }
    });
  } catch (error) {
    // 回滚事务
    await transaction.rollback();
    next(error);
  }
};

/**
 * 支付订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Object} next - 下一个中间件
 * @returns {Promise<any>}
 */
const payOrder = async (req, res, next) => {
  try {
    // 获取订单ID
    const orderId = req.params.id;
    console.log('[订单控制器] 支付订单，ID:', orderId);
    
    // 确保用户已登录
    if (!req.user || !req.user.id) {
      return res.status(401).json({
        code: 401,
        message: '请先登录'
      });
    }
    
    // 查找订单
    const order = await Order.findOne({
      where: {
        id: orderId,
        user_id: req.user.id
      }
    });
    
    // 订单不存在或不属于当前用户
    if (!order) {
      return res.status(404).json({
        code: 404,
        message: `订单#${orderId}不存在`
      });
    }

    console.log(`[订单控制器] 找到订单:`, {
      id: order.id,
      orderNo: order.order_no,
      status: order.status,
      amount: order.total_amount
    });

    // 检查订单状态是否为待支付
    if (order.status !== 0) {
      return res.status(400).json({
        code: 400,
        message: '该订单不是待支付状态，无需支付'
      });
    }

    // 开发环境模拟支付
    if (process.env.NODE_ENV === 'development' && process.env.MOCK_PAYMENT === 'true') {
      console.log('[订单控制器] 开发环境，返回模拟支付参数');
      
      // 生成模拟支付参数
      const mockPayParams = {
        timeStamp: Math.floor(Date.now() / 1000).toString(),
        nonceStr: Math.random().toString(36).substr(2, 15),
        package: 'prepay_id=wx' + Date.now(),
        signType: 'MD5',
        paySign: 'MOCK_SIGN_' + Date.now()
      };
      
      return res.status(200).json({
        code: 200,
        message: '获取支付参数成功(模拟)',
        data: mockPayParams
      });
    }

    // 获取微信支付统一下单参数
    const wxpay = require('../../utils/wxpay'); // 微信支付工具模块
    
    // 检查用户openid
    if (!req.user.openid) {
      console.error('[订单控制器] 用户缺少openid:', req.user);
      return res.status(400).json({
        code: 400,
        message: '用户信息不完整，缺少openid'
      });
    }
    
    // 计算支付金额（单位：分）- 确保为整数
    const total_fee = Math.round(order.total_amount * 100);
    if (total_fee <= 0) {
      return res.status(400).json({
        code: 400,
        message: '订单金额必须大于0'
      });
    }

    // 订单描述
    const body = `商城订单-${order.order_no}`;
    
    // 获取客户端IP
    const spbill_create_ip = req.headers['x-forwarded-for'] || 
                            req.connection.remoteAddress || 
                            req.socket.remoteAddress || 
                            req.ip || 
                            '127.0.0.1';

    console.log('[订单控制器] 开始调用微信统一下单接口:', {
      orderNo: order.order_no,
      totalFee: total_fee,
      openid: req.user.openid,
      spbill_create_ip: spbill_create_ip,
      body: body
    });

    // 调用统一下单接口
    const payResult = await wxpay.unifiedOrder({
      openid: req.user.openid, // 用户openid
      body: body,              // 商品描述
      out_trade_no: order.order_no, // 商户订单号
      total_fee: total_fee,    // 总金额(分)
      spbill_create_ip: spbill_create_ip, // 终端IP
      notify_url: process.env.WXPAY_NOTIFY_URL || wxpay.wxpayConfig.notifyUrl, // 支付结果通知地址
      trade_type: 'JSAPI'      // 交易类型
    });
    
    console.log('[订单控制器] 微信统一下单结果:', payResult);
    
    if (payResult.return_code === 'SUCCESS' && payResult.result_code === 'SUCCESS') {
      // 统一下单成功，生成小程序支付参数
      const prepay_id = payResult.prepay_id;
      
      // 更新订单预支付ID
      await order.update({
        prepay_id: prepay_id
      });
      
      // 生成小程序支付参数
      const payParams = wxpay.getPayParams(prepay_id);
      console.log('[订单控制器] 生成的支付参数:', payParams);
      
      // 返回支付参数给前端
      return res.status(200).json({
        code: 200,
        message: '获取支付参数成功',
        data: payParams
      });
    } else {
      const errorMsg = payResult.err_code_des || payResult.return_msg || '未知错误';
      console.error('[订单控制器] 微信支付下单失败:', errorMsg);
      
      return res.status(500).json({
        code: 500,
        message: '微信支付下单失败: ' + errorMsg
      });
    }
   
  } catch (error) {
    console.error('[订单控制器] 支付订单出错:', error);
    return res.status(500).json({
      code: 500,
      message: '支付处理异常: ' + (error.message || '未知错误')
    });
  }
};

/**
 * 处理支付结果通知
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Promise<void>}
 */
exports.handlePaymentNotify = async (req, res) => {
  try {
    // 1. 解析微信返回的XML数据
    const rawData = req.rawBody.toString();
    
    // 将XML转换为JS对象
    const parser = new xml2js.Parser({ explicitArray: false, trim: true });
    const result = await new Promise((resolve, reject) => {
      parser.parseString(rawData, (err, result) => {
        if (err) reject(err);
        else resolve(result);
      });
    });
    
    const notifyData = result.xml;
    
    // 2. 验证签名
    const isSignValid = wxpay.verifyPaymentNotify(notifyData);
    if (!isSignValid) {
      console.error('支付通知签名验证失败');
      return res.send('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>');
    }
    
    // 3. 检查支付结果
    if (notifyData.return_code === 'SUCCESS' && notifyData.result_code === 'SUCCESS') {
      const orderNo = notifyData.out_trade_no;
      const transactionId = notifyData.transaction_id;
      
      // 4. 更新订单状态
      const order = await Order.findOne({ where: { order_no: orderNo } });
      
      if (!order) {
        console.error(`未找到订单: ${orderNo}`);
        return res.send('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[订单不存在]]></return_msg></xml>');
      }
      
      // 避免重复处理
      if (order.status !== ORDER_STATUS.PENDING_PAYMENT) {
        console.warn(`订单 ${orderNo} 已被处理过，当前状态: ${order.status}`);
        return res.send('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
      }
      
      // 更新订单状态为待发货
      await order.update({
        status: ORDER_STATUS.PENDING_DELIVERY,
        payment_time: new Date(),
        transaction_id: transactionId
      });
      
      console.log(`订单 ${orderNo} 支付成功处理完成`);
      
      // 5. 返回成功消息给微信服务器
      return res.send('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
    } else {
      console.error(`支付失败: ${notifyData.return_msg}`);
      return res.send('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[支付结果验证失败]]></return_msg></xml>');
    }
  } catch (error) {
    console.error('处理支付通知时出错:', error);
    return res.send('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[服务器内部错误]]></return_msg></xml>');
  }
};

module.exports = {
  getOrders: exports.getOrders,
  getRecentOrders: exports.getRecentOrders,
  getOrderById: exports.getOrderById,
  cancelOrder: exports.cancelOrder,
  createOrder: exports.createOrder,
  payOrder: payOrder,
  handlePaymentNotify: exports.handlePaymentNotify
}; 